import { useState } from 'react';
import moment from 'moment';
import { Modal, DatePicker, Select, Form, Button, Input } from 'antd';
import MemberSelect from '@inbiz/basic/MemberSelect';
import { observer } from '@formily/react';
import { TextWidget, getMessage } from '@inbiz/react';
import { afterOperation } from '../../utils';
import { setFutureTask } from '../../service';
import './index.less';

const { Option } = Select;
const FormItem = Form.Item;
const formLayout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 16,
  },
};
const dateFormat = 'YYYY-MM-DD';
export default observer((props: any) => {
  const { visible, $visible, applyList, userInfo, searchApplyList, choosedTabKey } = props;
  const [persons, $persons] = useState([]);
  const [form] = Form.useForm();
  const [memberSelectVisible, $memberSelectVisible] = useState(false);
  const { getFieldsValue, setFieldsValue, resetFields } = form;

  const comfirmAssign = () => {
    const values = getFieldsValue();
    const parasm = {
      assignee: userInfo?.ID,
      attorney: persons.map((item) => item.id).join(','),
      endTime: moment(values.endTime).format('YYYY-MM-DD 23:59:59'),
      processKey: values.process,
      status: '1',
      stratTime: moment(values.startTime).format('YYYY-MM-DD 00:00:00'),
    };
    setFutureTask(parasm).then((res) => {
      afterOperation(
        { ...res, message: `${getMessage('global.save')}${getMessage('processCenter.success')}` },
        () => {
          $visible(false);
          resetFields();
          searchApplyList(choosedTabKey);
        },
      );
    });
  };

  const disabledDate = (current) => {
    return current && current < moment().startOf('day');
  };
  return (
    <Modal
      title={getMessage('processCenter.setWillAssign')}
      visible={visible}
      className="setFutureAssign"
      footer={null}
      onCancel={() => {
        $visible(false);
        resetFields();
      }}
      centered
      width={700}
      destroyOnClose
      bodyStyle={{ height: 300, marginTop: 25 }}
    >
      <Form form={form} {...formLayout} onFinish={comfirmAssign}>
        <FormItem
          name="process"
          label={getMessage('processCenter.process')}
          rules={[{ required: true, message: getMessage('processCenter.selectProcesstips') }]}
        >
          <Select placeholder={getMessage('processCenter.select')} allowClear>
            {/* {applyList.slice(1).map((item) => {
              return (
                <Option value={item.ProcessKey} key={item.ProcessKey}>
                  {item.ProcessName}
                </Option>
              );
            })} */}
            {applyList.map((item) => {
              return (
                <Option value={item.ProcessKey} key={item.ProcessKey}>
                  {item.ProcessName}
                </Option>
              );
            })}
          </Select>
        </FormItem>
        <FormItem
          name="person"
          label={getMessage('processCenter.assignto')}
          rules={[{ required: true, message: getMessage('processCenter.selectBeenAssigned') }]}
          onClick={() => $memberSelectVisible(true)}
        >
          <Input
            placeholder={getMessage('processCenter.select')}
            allowClear
            autoComplete="off"
            onChange={(e) => {
              if (!e.target.value) {
                $persons([]);
                setFieldsValue({ person: '' });
              }
            }}
          />
        </FormItem>
        <FormItem
          name="startTime"
          label={getMessage('processCenter.from')}
          rules={[{ required: true, message: getMessage('processCenter.selectstarttime') }]}
        >
          <DatePicker
            style={{ width: '100%' }}
            allowClear
            format={dateFormat}
            disabledDate={disabledDate}
          />
        </FormItem>
        <FormItem
          name="endTime"
          label={getMessage('processCenter.to')}
          rules={[
            { required: true, message: getMessage('processCenter.selectendTime') },
            ({ getFieldValue }) => ({
              validator(_, value) {
                const stTime = getFieldValue('startTime');
                if (stTime && value && moment(value).valueOf() > moment(stTime).valueOf()) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error(`${getMessage('processCenter.reselectTime')}`));
              },
            }),
          ]}
        >
          <DatePicker
            style={{ width: '100%' }}
            allowClear
            format={dateFormat}
            disabledDate={disabledDate}
          />
        </FormItem>
          <div style={{ display: 'flex', justifyContent: 'center'}}>
            <div style={{ width: 145 }}>
            <Button type="primary" htmlType="submit" style={{ marginRight: 15, marginBottom: 20 }}>
              <TextWidget>global.sure</TextWidget>
            </Button>
            <Button
              htmlType="button"
              onClick={() => {
                $visible(false);
                resetFields();
              }}
            >
              <TextWidget>processCenter.close</TextWidget>
            </Button>
            </div>
          </div>
      </Form>
      <MemberSelect
        visible={memberSelectVisible}
        config={{
          pageSize: 10,
          multiple: false,
          tabs: ['user'],
          selected: persons,
          onOk: (keys, selected, map) => {
            setFieldsValue({ person: selected.map((item) => item.name).join(',') });
            $persons(selected);
            $memberSelectVisible(false);
          },
          onCancel: () => {
            $persons([]);
            $memberSelectVisible(false);
          },
        }}
      />
    </Modal>
  );
});
